#include "KStars.h"
#include "StarEntry.h"
#include <qtextstream.h>
#include <qstringlist.h>
#include <libnova.h>

/*
# Star catalog derived from the Hipparcos and Tycho star catalogs.
# These catalogs are in the public domain, and can be obtained from
# http://cdsweb.u-strasbg.fr/viz-bin/Cat?I/239
#
# Changes made to the raw catalog include stripping out certain data
# fields, reformatting, and manual matching up common and genetive
# star names.  The modified catalog is (C) Jason Harris, 2003, and is
# licensed under the terms of the GNU General Public License (GPL):
# http://www.gnu.org/licenses/gpl.html
#
#  RA        DEC      pmRA     pmDEC  plx      mag  BV SpT b? dV   vper, genetive name, long name
#
064508.92 -164258.0 -000546.0-001223.100379.2 -1.4400.01A0 1            , alp CMa, Sirius
*/

void KStars::loadData()
{
  QString record;
  int maxrecordlength=123;
  int count=0;
  int fk5;
  int rah, ram;
  float ras, pmRA;
  int ded, dem;
  float des, pmDE;
  float epRA, epDE;
  float mag;
  char sp[2];
  char dm[10];
  QString names, hd;
  QString bfno;
  QString sname;
  double ra, dec;
  
  QString *uname;
  
  if (!datafile.open(QIODevice::ReadOnly | QIODevice::Text)) {
    printf("Catalog loadData: Can not open file %s\n", datafile.fileName().toAscii().data());
    return;
  }
  prefix = new QString("KS");
  
  QTextStream in(&datafile);
  //record[123]='\0';
 
  while (!in.atEnd()) {
    record=in.readLine();
    if (record[0] == '#') continue;
    if (mag > 6.0) break;
    //printf("Record%d\n%s\n", count, record.toAscii().data());
    //fk5=record.mid(0,4).toInt();
    rah=record.mid(0,2).toInt();
    ram=record.mid(2,2).toInt();
    ras=record.mid(4,5).toFloat();
    ra=rah +(ram / 60.0) + (ras / 3600.0);
    pmRA=(record.mid(20,9).toFloat());
    ded=record.mid(10,3).toInt();
    dem=record.mid(13,2).toInt();
    des=record.mid(15,4).toFloat();
    if (ded >= 0)
      dec=ded +(dem / 60.0) + (des / 3600.0);
    else
      dec=ded -(dem / 60.0) - (des / 3600.0);
    pmDE=record.mid(29,9).toFloat();
    mag=record.mid(46,5).toFloat();
    names=record.mid(59);
    QStringList l=names.split(',');

    if (l.count()  == 3)
      uname=new QString(l[1] + " - " + l[2]);
    else
      if (l.count() == 2)
        uname=new QString(l[1]);
      else 
	uname = new QString("");
    printf("Star %d: %d -- %g -- %g -- %g -- %s\n", count, fk5, ra, dec, mag, uname->toAscii().data());
    stars.insert(stars.end(), new StarEntry(count, count, JD2000, ra, dec, (pmRA / 3600000.0), (pmDE / 3600000.0), mag, *uname));
    count+=1;
  }
  emit layoutChanged();
  datafile.close();
}